package com.hjx.windowtool.photolook;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.JFrame;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JList;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.tree.DefaultTreeModel;

import com.hjx.windowtool.db.Tool;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JTextField;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionEvent;

@Tool("图片查看")
public class ImagesLookApp {

	private static final int CACHE_IMAGE_SIZE = 100;
	private JFrame frame;
	private TableModel dataModel;
	private JTextField txtGbaiduyundownloadlance;
	private JTextField textField_1;
	private JPanel panel;
	private List<File> listFile;
	private List<Image> images=new ArrayList<>();
	private boolean isStart=true;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					ImagesLookApp window = new ImagesLookApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public ImagesLookApp() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 714, 451);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JSplitPane splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.1);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		frame.getContentPane().add(splitPane, BorderLayout.CENTER);
		
		panel = new JPanel();
		splitPane.setRightComponent(panel);
		panel.setLayout(null);
		
		JPanel panel_1 = new JPanel();
		splitPane.setLeftComponent(panel_1);
		
		txtGbaiduyundownloadlance = new JTextField();
		txtGbaiduyundownloadlance.setText("G:\\BaiduYunDownload\\111\\lance\\2");
		panel_1.add(txtGbaiduyundownloadlance);
		txtGbaiduyundownloadlance.setColumns(40);
		
		textField_1 = new JTextField();
		textField_1.setText("25");
		panel_1.add(textField_1);
		textField_1.setColumns(10);
		
		JButton btnNewButton = new JButton("播放");
		btnNewButton.addActionListener(new ActionListener() {
			private ScheduledExecutorService loadImageService;
			private ScheduledExecutorService showImageService;

			public void actionPerformed(ActionEvent e) {
				if (loadImageService!=null) {
					loadImageService.shutdown();
				}
				if (showImageService!=null) {
					showImageService.shutdown();
				}
				String path = txtGbaiduyundownloadlance.getText();
				File dir=null;
				if (path==null||!(dir=new File(path)).exists()) {
					return;
				}
				File[] listFiles = dir.listFiles();
				listFile = new ArrayList<>(Arrays.asList(listFiles));
				listFile=Collections.synchronizedList(listFile);
				System.out.println(listFile.size());
				listFile.sort(new Comparator<File>() {
					@Override
					public int compare(File o1, File o2) {
						String name = o1.getName();
						String name2 = o2.getName();
						try {
							Integer valueOf = Integer.valueOf(name.substring(0, name.lastIndexOf(".")));
							Integer valueOf1 = Integer.valueOf(name2.substring(0, name2.lastIndexOf(".")));
							return valueOf.compareTo(valueOf1);
						} catch (Exception e2) {
						}
						return name.compareTo(name2);
					}
				});
				images.clear();
				for (int i = 0; i < Math.min(CACHE_IMAGE_SIZE, listFile.size()); i++) {
					File remove = listFile.remove(i);
					try {
						BufferedImage image = ImageIO.read(remove);
						images.add(image);
						System.out.println("读取图片完成："+remove);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
				loadImageService = Executors.newSingleThreadScheduledExecutor();
				loadImageService.scheduleAtFixedRate(new Runnable() {
					@Override
					public void run() {
						if (images.size()>=CACHE_IMAGE_SIZE) {
							return;
						}
						if (listFile.isEmpty()) {
							loadImageService.shutdown();
							return;
						}
						for (int i = 0; i < 3; i++) {
							File remove = listFile.remove(0);
							try {
								BufferedImage image = ImageIO.read(remove);
								images.add(image);
								System.out.println(images.size() + "=读取图片完成：" + remove);
							} catch (IOException e1) {
								e1.printStackTrace();
							} 
						}
					}
				}, 10, 10, TimeUnit.MILLISECONDS);
				int rate=1000/Integer.valueOf(textField_1.getText());
				showImageService = Executors.newSingleThreadScheduledExecutor();
				showImageService.scheduleAtFixedRate(new Runnable() {

					@Override
					public void run() {
						if (!isStart) {
							return;
						}
						System.out.println(images.size()+"=="+listFile.isEmpty());
						if (images.isEmpty()) {
							if(listFile.isEmpty()) {
								showImageService.shutdown();
							}
							return;
						}
						Rectangle bounds = panel.getBounds();
						System.out.println(bounds);
						Graphics g = panel.getGraphics();
						Image img = images.remove(0);
						
						g.drawImage(img, 0, 0,bounds.width,bounds.height, panel);
					}
				}, rate, rate, TimeUnit.MILLISECONDS);
			}
		});
		panel_1.add(btnNewButton);
		
		JButton button = new JButton("暂停");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				isStart=!isStart;
				button.setText(isStart?"暂停":"开始");
			}
		});
		panel_1.add(button);
	}
	
	class TableModel extends DefaultTableModel{
		private static final long serialVersionUID = 1L;
		String[] cloumns=new String[] {"图片"};
		public List<String[]> rows=new ArrayList<>();
		
		public List<String[]> getRows() {
			return rows;
		}
		public void setRows(List<String[]> rows) {
			this.rows = rows;
			fireTableDataChanged();
		}
		@Override
		public int getRowCount() {
			return rows.size();
		}
		@Override
		public String getColumnName(int column) {
			return cloumns[column];
		}
		@Override
		public int getColumnCount() {
			return cloumns.length;
		}
		@Override
		public Object getValueAt(int row, int column) {
			return rows.get(row)[column];
		}
	}
}
